﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Globalization;

using CE.CarInsurance;
using CE.User;
using CE.Mail;
using CE.Global;
using CE.Database;

public partial class signup_promo_promotion :  CE.Global.MyLanguageBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.SignUp.PageTitle;

        HtmlLink cssButton = new HtmlLink();
        cssButton.Href = Resources.General.CssButtonUrl;
        cssButton.Attributes["rel"] = "stylesheet";
        cssButton.Attributes["type"] = "text/css";
        cssButton.Attributes["media"] = "all";
        Page.Header.Controls.Add(cssButton);

        HtmlLink cssLink = new HtmlLink();
        cssLink.Href = Resources.SignUp.CssUrl;
        cssLink.Attributes["rel"] = "stylesheet";
        cssLink.Attributes["type"] = "text/css";
        cssLink.Attributes["media"] = "all";
        Page.Header.Controls.Add(cssLink);

        if (!Page.IsPostBack)
        {
            LoadManufactYearList();

            txtName.Attributes.Add("onblur", "ShowValidationEffect('" + txtName.ClientID + "','" + rfvName.ClientID + "');");
            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvExEmail.ClientID + "','" + rfvExEmailValid.ClientID + "');");

            DateTime dtNow = new DateTime();
            dtNow = DateTime.Now;        

            for (int i = 0; i < 12; i++)
            {
                ddlRenewalMonth.Items.Add(new ListItem(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i], (i+1).ToString()));
            }

            ddlRenewalMonth.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
    }

    protected void btnSignUp_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("subscribed");
            SortedList _spList = new SortedList();
            _spList.Add("@Mobile", txtMobileNo.GetPhoneNo());
            _dt = _db.GetDataTableBySP("sprocSignUpFormSelectSingleItem", _spList);


            if (_dt.Rows.Count == 0)
            {
                
                string _spName = "[sprocSignUpFormInsertUpdateSingleItem]";

                SortedList _spList2 = new SortedList();
                _spList2.Add("@SignUpId", 0);
                _spList2.Add("@CustomerName", txtName.Text.Trim());
                _spList2.Add("@Mobile", txtMobileNo.GetPhoneNo());
                _spList2.Add("@EmailAddress", txtEmail.Text.Trim());
                _spList2.Add("@CarMakeModel", ddlCarMake.SelectedItem.Text + " - " + ddlModelBodyCCDoor.SelectedItem.Text);

                //DateTime dtRenewal = Convert.ToDateTime("1/" + ddlRenewalMonth.SelectedItem.Value.ToString() + "/" + DateTime.Now.Year.ToString());
                //DateTime dtRenewal = Convert.ToDateTime((Convert.ToDateTime(ddlRenewalMonth.SelectedValue.ToString() + "/01/" + DateTime.Now.Year.ToString()).ToString(new CultureInfo("en-US"))));
                string sdate = ddlRenewalMonth.SelectedValue.ToString() + "/01/" + DateTime.Now.Year.ToString();
                DateTime dtRenewal = DateTime.Parse(sdate, CultureInfo.InvariantCulture);

                //if (HttpContext.Current.Session["Language"] != null)
                //{
                //    if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                //    {
                //        dtRenewal = Convert.ToDateTime("01/" + ddlRenewalMonth.SelectedValue.ToString() + "/" + DateTime.Now.Year.ToString());
                //    }
                //}
                _spList2.Add("@RenewalMonth",dtRenewal);

                Int64 _retValue = _db.ExecuteSP(_spName, _spList2);

                if (_retValue > 0)
                {
                    Int64 _userId = 0;

                    _userId = SaveNewCustomer();

                    //if (Session[General.UserId] == null)
                    //{
                    //    _userId = SaveNewCustomer();
                    //}
                    //else
                    //{
                    //    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                    //    UpdateProfile(_userId, 0);
                    //}

                    if (_userId > 0 && Save(_userId))
                    {
                        this.EmailQuote(_retValue);

                        btnSignUp.Enabled = false;
                        txtName.Enabled = false;
                        txtEmail.Enabled = false;
                        txtMobileNo.IsEnabled = false;
                        ddlManufactYear.Enabled = false;
                        ddlCarMake.Enabled = false;
                        ddlModelBodyCCDoor.Enabled = false;
                        ddlRenewalMonth.Enabled = false;

                        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                        if (UpdateProfile(_userId, _carId) > 0)
                        {
                            lblMessage.Text = Resources.SignUp.Thankyou.ToString();
                        }
                    }


                }
            }
            else
            {
                lblMessage.Text = Resources.SignUp.ExistingSubscriber.ToString();
            }

        }
    }

    private void LoadManufactYearList()
    {
        int _yearCount = 10;
        ddlManufactYear.Items.Clear();

        _yearCount = 20;
         
            int _startYear = DateTime.Now.Year - _yearCount;
            int _endYear = DateTime.Now.Year;
            for (int i = _endYear; i >= _startYear; i--)
            {
                //ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                if (CultureInfo.CurrentCulture.Name != "th-TH")
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                else
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
                }
            }
        
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(10000);
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

            txtSumInsured.Text = "0";
            //lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][0].ToString()));
            }
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            //if (rdoYesAccMod.Checked)
            //{
            //    if (txtAccModAmount.Text.Length > 0)
            //    {
            //        int _sumInsured = Convert.ToInt32(txtSumInsured.Text);
            //        int _tmpAmount = 0;
            //        if (Int32.TryParse(txtAccModAmount.Text, out _tmpAmount))
            //        {
            //            _sumInsured += _tmpAmount;
            //            txtNewSumInsured.Text = _sumInsured.ToString();
            //            lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
            //        }
            //        else
            //        {
            //            txtNewSumInsured.Text = _sumInsured.ToString();
            //            txtAccModAmount.Text = "";
            //        }
            //    }
            //}
            //ChangeVehicleUsageList(lblCarVehicleType.Text);
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Init_JTip_Driver", "JT_init();", true);
            //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ShowHide_AccMod", "CheckAccMod();", true);
            //CheckAccMod()
        }
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
            //txtTextBox.Text = string.Format("{0:#,0}", _dt.Rows[0][0]);
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.Text == "-1")
        {
            ClearAllList();
        }
        else
        {
            GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
            if (ddlCarMake.Items.Count > 0)
            {
                ddlCarMake.SelectedIndex = 0;
                ddlCarMake_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        //ddlCarMake.Items.Add(new ListItem("Test", "TEST"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void EmailQuote(Int64 signupid)
    {
        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        _emailList = txtEmail.Text.Trim();
        _title = "";

        _title = Resources.SignUp.EmailSubject; 


        _message.Append(Resources.SignUp.EmailDear + " " + txtName.Text.Trim() + ",");
        _message.Append("<br/><br/>");
        _message.Append(Resources.SignUp.EmailThankYou);
        _message.Append("<br/><br/>");
        _message.Append(Resources.SignUp.EmailCash + "TL0000" + signupid.ToString());
        _message.Append("<br/><br/>");
        _message.Append(Resources.SignUp.EmailDeliver);
        _message.Append("<br/><br/>");
        _message.Append(Resources.SignUp.EmailFooter);
        _message.Append("<br/>");
        _message.Append(Resources.SignUp.EmailGGTeam);
        _message.Append("<br/><br/>");
        if (HttpContext.Current.Session["Language"] != null)
        {
            if (HttpContext.Current.Session["Language"].ToString() != "th-TH")
                _message.Append("<br/>");
        }
        _message.Append("<i>" + Resources.SignUp.EmailDisclaimer + "</i><hr />");

        MyMailManager.SendSignUpMessage(_emailList, _title, _message.ToString());
        
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        bool _isEmailExist = false;
        
        Account _useraccount = new Account();
        AccountDB _useraccountdb = new AccountDB();

        Profile _userprofile = new Profile();
        ProfileDB _userprofiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        //if (_useraccountdb.IsAlreadyExist(txtEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
        //{
        //    _isEmailExist = true;
        //    //divNewErrorMessage.Visible = true;
        //    //lblCarInsProfileMessage.Text = "Email address is already registered!";

        //    _useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), 400);

        //    if (_useraccount != null && _useraccount.CEID > 0)
        //    {
        //        _contact = _contactdb.GetContact(_useraccount.CEID);
        //        if (_contact.Mobile == txtMobileNo.GetPhoneNo())
        //        {
        //            UpdateProfile(_useraccount.CEID, 0);

        //            _profile = _profiledb.GetProfile(_useraccount.CEID);
        //            Session[CE.Global.General.UserId] = _useraccount.CEID;
        //            Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
        //            Session[CE.Global.General.UserEmail] = _useraccount.Email;
        //            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        //            Session[CE.Global.General.StartTime] = DateTime.Now.ToString();
        //            _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
        //            if (_userprofile != null && _userprofile.ProfileId > 0)
        //            {
        //                if (_userprofile.FirstName != string.Empty)
        //                {
        //                    Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
        //                }
        //                else
        //                {
        //                    Session[CE.Global.General.UserName] = _userprofile.SurName;
        //                }
        //            }
        //            _retVal = _useraccount.CEID;
        //        }
        //        else
        //        {
        //            txtEmail.ControlStyle.CssClass = "validationError";
        //            _retVal = 0;
        //        }
        //    }
        //    else
        //    {
        //        txtEmail.ControlStyle.CssClass = "validationError";
        //        _retVal = 0;
        //    }
        //}

        if (_retVal == 0 && _isEmailExist == false)
        {
            long _result = -1;
            //divNewErrorMessage.Visible = false;
            //lblCarInsProfileMessage.Visible = false;

            _useraccount.Email = txtEmail.Text.ToLower();

            //Random _random = new Random();
            string _authcode = txtMobileNo.GetPhoneNo();
            //Sakthi on 21 Jan 2011
            //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
            //_authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

            _useraccount.AuthCode = _authcode;

            _useraccount.UserId = "CEUSERAUTOIDPROMOCI";
            _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
            _useraccount.IsAcceptTC = false;
            _useraccount.Status = true;
            _useraccount.RefCEUserID = -1;

            _result = _useraccountdb.Insert(_useraccount);
            _useraccount.CEID = _result;
            _retVal = _useraccount.CEID;

            if (_result > 0)
            {
                _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
                _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                _userprofile.SurName = ""; // Server.HtmlEncode(txtLastName.Text);

                DateTime _dtDOB = new DateTime(1900, 1, 1);
                _userprofile.DOB = _dtDOB;

                _userprofile.DOB = DateTime.Now.AddYears(-20); //usrDOB.GetDate();
                _userprofile.Gender = Convert.ToChar("M"); //default Convert.ToChar(ddlGender.Text);

                //_userprofile.MaritalStatus = Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                //_userprofile.JobNature = ddlJobNature.GetJobNature();
                _userprofile.Occupation = 140; // Convert.ToInt32(ddlOccupation.GetOccupation());
                //_userprofile.YearDriveSg = Convert.ToInt16(ddlYearDriveSg.Text);
                _userprofile.Status = "Complete";
                _userprofile.RefCEUserId = _useraccount.CEID;
                _userprofile.IsAcceptTC = true;
                //_userprofile.Info1 = "TESCO200";
                _result = _userprofiledb.Insert(_userprofile);

                _contact.Email = _useraccount.Email;
                _contact.Mobile = txtMobileNo.GetPhoneNo();

                _contact.Status = true;
                _contact.RefCEUserId = _useraccount.CEID;
                _result = _contactdb.Insert(_contact);

                if (_result > 0)
                {
                    SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);                   
                  
                }

            }
        }

        return _retVal;
        #endregion
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                _profile.FirstName = txtName.Text;
                _profile.SurName = ""; // txtLastName.Text;
                _profile.DOB = DateTime.Now.AddYears(-20); // usrDOB.GetDate();
                _profile.Gender = Convert.ToChar("M");

                _profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _profile.JobNature = "";// ddlJobNature.GetJobNature();
                _profile.Occupation = 140; // Convert.ToInt32(ddlOccupation.GetOccupation());
                _profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    //divNewErrorMessage.Visible = true;
                    //lblCarInsProfileMessage.Text = "Error found in profile update!";
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    //if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    //    Convert.ToInt32(CE.Global.CEUserType.Provider))
                    //{
                    //    Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    //}
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }

        //if (_retValue > 0)
        //{
        //    CarDetailTH _cardetail = new CarDetailTH();
        //    CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        //    _cardetail = _cardetaildb.GetCar(CarId, UserId);

        //    if (_cardetail != null)
        //    {
        //        _cardetail.Info5 = txtEmail.Text;
        //        _cardetail.Info6 = ddlMobile.Text + txtPhoneNum.Text;
        //        _cardetail.Info7 = ""; // txtLastName.Text;
        //        if (txtFirstName.Text.Trim().Length > 0)
        //        {
        //            _cardetail.Info8 = txtFirstName.Text.Trim();
        //        }
        //        //CultureInfo ci = CultureInfo.CurrentCulture;
        //        _cardetail.Info9 = ddlGender.Text;
        //        _cardetail.Info10 = usrDOB.GetDate().ToString("dd-MMM-yyyy");
        //        _cardetail.Info11 = ddlOccupation.GetOccupation();
        //        _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
        //        _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
        //        _cardetail.Info14 = "";// ddlYearDriveSg.Text;
        //        _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
        //        _cardetail.RefCEUserId = UserId;
        //    }

        //    //RefUserId only update
        //    CarPolicy _carpolicy = new CarPolicy();
        //    CarPolicyDB _carpolicydb = new CarPolicyDB();
        //    _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
        //    _carpolicy.RefCEUserId = UserId;

        //    _retValue = _cardetaildb.Insert(_cardetail);

        //    _retValue = _carpolicydb.Insert(_carpolicy);

        //    //update RefIds
        //    CarDetailTHDB cardb = new CarDetailTHDB();
        //    cardb.UpdateCarDetailPolicy(CarId, UserId);

        //    if (_retValue <= 0)
        //    {
        //        //divNewErrorMessage.Visible = true;
        //        //lblCarInsProfileMessage.Text = "Error found in car quote profile update";
        //    }
        //}

        return _retValue;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = DateTime.Now;
        _loghis.EndTime = DateTime.Now;
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    private bool Save(Int64 _refceuserid)
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        //Int64 _refceuserid = 0;


        //if (Session[General.CarId] != null)
        //{
        //    //_car.CECarId = Convert.ToInt64(Session[General.CarId].ToString());
        //    _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
        //    if (Session[General.AgentId] != null)
        //    {
        //        _car.Info5 = "UPDATE";
        //    }
        //}
        //else
        //{
        //    if (Session[General.AgentId] != null)
        //    {
        //        _car.Info4 = "NEW";
        //    }
        //}

        //if (Session[General.ViewedDetailsId] == null)
        //{
        //    Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
        //}

        //if (_car == null)
        //{
        //    _car = new CarDetailTH();
        //}

        if (_refceuserid > 0)
        {
            //_refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
            _profile = _profiledb.GetProfile(_refceuserid);
            _contact = _contactdb.GetContact(_refceuserid);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;//txtFirstName.Text.Trim();
                }
                _car.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _car.Info11 = _profile.Occupation.ToString();// ddlOccupation.GetOccupation();
                _car.Info12 = _profile.JobNature;//ddlJobNature.GetJobNature();
                _car.Info13 = _profile.MaritalStatus.ToString();//ddlMaritalStatus.GetMaritalStatus();
                _car.Info14 = "0"; //ddlYearDriveSg.Text;
                _car.Info15 = _profile.Salutation;//ddlSalutation.GetSalutation();
                _profile = null;
                _contact = null;
            }
        }



        //_car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);
        _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);

        //if (Session[General.AgentId] != null)
        //{
        //    _car.Info2 = Session[General.AgentId].ToString();
        //    _car.Info3 = DateTime.Now.ToString();
        //}

        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;

        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = ddlVehicleType.Text;
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "210";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "220";
            }
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "320";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "340"; //Disabled, No Packages
            }
        }

        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        _car.ViewedDetailId = 0;
        _car.CurrentStep = 1;
        _car.TotalStep = 4;

        //if (_refceuserid != 0)
        //{
        //    _profile = _profiledb.GetProfile(_refceuserid);
        //    if (_profile != null)
        //    {
        //        //Save User Profile
        //        _car.Info10 = _profile.SurName.ToString();
        //        _car.Info11 = _profile.Gender.ToString();
        //        _car.Info12 = _profile.DOB.ToString("dd-MMM-yyyy");
        //        _car.Info13 = _profile.Occupation.ToString();
        //        _car.Info14 = _profile.JobNature.ToString();
        //        _car.Info15 = _profile.MaritalStatus.ToString();
        //        _car.Info16 = _profile.YearDriveSg.ToString();
        //    }
        //}
        _car.Info1 = "150"; // ddlCurInsuranceCompany.Text; //Current Insurer ID

        _carresult = _cardb.Insert(_car);
        _car.CarId = _carresult;

        //return _result > 0;
        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = _car.CarId;

            Int64 _carpolicyid = 0;

            lblMessage.Text = "";
            
            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = 10; // Convert.ToInt32(ddlInsuranceClass.Text);
            _carpolicy.GarageType = 1; // Convert.ToInt32(ddlGarageType.Text);
            _carpolicy.VehicleType = 110; // Convert.ToInt32(ddlVehicleType.Text);
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text.Replace(",", ""));
            _carpolicy.ProvinceRegistration = "BKK"; // ddlProvinceRegistration.Text;
            _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;
            //string strDate = DateTime.Now.ToString("ddmmyyyy"); //ddlCoverageComDate.Text;
            //int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
            //int _iMonth = Convert.ToInt32(strDate.Substring(2, 2));
            //int _iYear = Convert.ToInt32(strDate.Substring(4, 4));
            //_carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay);
            _carpolicy.CoverageCommenceDate = DateTime.Now.AddDays(30);
            _carpolicy.IsRedPlate = false; //rdoYesRedPlate.Checked;

            _carpolicy.IsAddAccMod = false; // rdoYesAccMod.Checked;

        
            _carpolicy.NCDPercent = 20; // Convert.ToInt32(ddlNCB.Text);
  
            _carpolicy.IsClaimLastYear = false; // rdoYesClaimLastYear.Checked;
            _carpolicy.IsCTPL = false; // rdoYesCTPL.Checked;

            _carpolicy.IsAddDriver = false; // rdoYesAddDriver.Checked;

            //_carpolicy.Deductible = 0;
            _carpolicy.Deductible = 0; // Convert.ToInt16(ddlDeduct.SelectedValue);
            _carpolicy.CurrentInsurer = "Others"; // ddlCurInsuranceCompany.SelectedItem.Text;
            _carpolicy.RefCEUserId = _refceuserid;
            //_carpolicy.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
            _carpolicy.ViewedDetailId = 0;
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _carpolicy.Info8 = "TESCO200";
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                Session[General.CarPolicyId] = _policyresult.ToString();

                //lblMessage.Text += "<br>Car policy saved successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            _carpolicy = null;
            _carpolicydb = null;
            _car = null;
            _cardb = null;

        }

        return _policyresult > 0;
    }
}
